package com.portal.framework.exception.handler;

import java.text.MessageFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.portal.framework.exception.ExceptionHandleException;
import com.portal.framework.util.ClassUtil;

/**
 * 异常中的内容包含给定的字符则变成一个特定信息(message)的异常(ExceptionHandleException)
 * 
 * @author 卢烁波
 * @date 2007-3-10
 */
public class ContentMsgNestedExceptionHandler extends AbstractExceptionHandler {

	private static final Log log = LogFactory
			.getLog(ContentMsgNestedExceptionHandler.class);

	private String msg;
	private String includeContent;

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public ContentMsgNestedExceptionHandler(String msg) {
		this.msg = msg;
	}

	public ContentMsgNestedExceptionHandler(
			Class<? extends Throwable> exceptionClass, String msg) {
		this.msg = msg;
		this.exceptionClass = exceptionClass;
	}

	public ContentMsgNestedExceptionHandler(
			Class<? extends Throwable> exceptionClass, String includeContent,
			String exceptionMsg) {
		this.msg = exceptionMsg;
		this.includeContent = includeContent;
		this.exceptionClass = exceptionClass;
	}

	public void handle(Throwable e) throws Throwable {
		if (log.isDebugEnabled()) {
			String exceptionMsg = "进行异常处理...异常类为[{0}],异常处理类为[{1}],要包含的内容为[{2}],异常信息为[{3}]";
			log.debug(MessageFormat.format(exceptionMsg,
					e.getClass().getName(), this.getClass().getName(),
					includeContent, msg));
		}

		e.printStackTrace();

		throw new ExceptionHandleException(msg, super.getStackTraceInfo(e));
	}

	@Override
	public String toString() {
		return MessageFormat.format("信息内容包含异常类处理.信息=[{0}],处理的异常=[{1}],要包含的内容为[{2}]", msg,
				this.exceptionClass.getName(),includeContent);
	}

	public boolean isMatch(Throwable e) {
		if (getExceptionClass() == null || e == null) {
			return false;
		}

		if ((e.getClass() == exceptionClass || ClassUtil.isExtendFrom(e.getClass(), exceptionClass))&& e.getMessage() != null
				&& e.getMessage().contains(includeContent)) {
			return true;
		} else {
			if (e.getCause() != null) {
				return isMatch(e.getCause());
			}
		}

		return false;
	}
}
